package com.weixin.base.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.thoughtworks.xstream.XStream;
import com.weixin.base.service.AdminSiteService;
import com.weixin.base.service.SiteService;
import com.weixin.base.util.ExtJsPageHelper;
import com.weixin.base.util.ListRange;
import com.weixin.base.util.MenuManager;
import com.weixin.base.util.PropertiesFile;
import com.weixin.base.util.Tools;
import com.weixin.entity.TbWxCustomMenu;
import com.weixin.entity.TbWxMenu;
import com.weixin.entity.TbWxText;
import com.weixin.entity.message.Menu;

@Controller
public class AdminSiteAction {

	@Autowired
	private PropertiesFile propertiesFile;

	@Autowired
	private AdminSiteService adminSiteService;

	/**
	 * 添加菜单记录 类型 1幻灯片2菜单
	 */
	@RequestMapping(value = "/module/main/saveAdminSiteMenu.do")
	public void saveAdminSiteMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		String picUrl = "";
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;

		TbWxMenu tbWxMenu = new TbWxMenu();
		tbWxMenu.setDCreateTime(new Date());
		// 类型 1幻灯片图片2菜单图片
		tbWxMenu.setNtype(Tools.convertRi(request.getParameter("ntype")));
		tbWxMenu.setSPicUrl(picUrl);
		tbWxMenu.setNUserId(Tools.convertRi(request.getParameter("userid")));
		tbWxMenu.setSContent(Tools.convertRs(request.getParameter("sContent")));
		tbWxMenu.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMenu.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMenu.setNOrder(Tools.convertRi(request.getParameter("nOrder")));

		if(tbWxMenu.getNUserId()<=0){
			result = 4;
			response.getWriter().print("{save:'true',success:'" + result + "'}");
			return;
		}
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("txtpath");

		if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
			String filenameold = file.getOriginalFilename();
			String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

			if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

				String newfilename = Tools.radomName(3) + hz;
				InputStream input = file.getInputStream();

				String folderPath = propertiesFile.getImagefolderPath() + tbWxMenu.getNUserId() + "\\";
				if (Tools.upload(newfilename, input, folderPath)) {
					picUrl = propertiesFile.getImageUrlPath() + tbWxMenu.getNUserId() + "/" + newfilename;
				}

			} else {
				result = 3;
				response.getWriter().print("{save:'true',success:'" + result + "'}");
				return;
			}
		}

		tbWxMenu.setSPicUrl(picUrl);
		result = adminSiteService.saveSiteMenu(tbWxMenu);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 查询菜单消息 ntype：消息类型（1幻灯片2菜单）
	 */
	@RequestMapping(value = "/module/main/searchAdminSiteMenu.do")
	public void searchAdminSiteMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		int userid = Tools.convertRi(request.getParameter("userid"));
		int ntype = Tools.convertRi(request.getParameter("ntype"));
		Page page = adminSiteService.searchSiteMenu(pr, userid, ntype);
		List tblist = (List) page.getResult();
		ListRange resultList = new ListRange();
		resultList.setList(tblist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		String result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
	}

	/**
	 * 修改菜单消息记录
	 */
	@RequestMapping(value = "/module/main/updateAdminSiteMenu.do")
	public void updateAdminSiteMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败 3.图片格式不正确（仅支持JPG、PNG）
		 */
		int result = 2;
		/**
		 * picUrl :标识图片是否改变 值为1不改变 其余表示改变
		 */
		String picUrl = Tools.convertRs(request.getParameter("spicUrl"));

		TbWxMenu tbWxMenu = new TbWxMenu();
		tbWxMenu.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxMenu.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxMenu.setSContent(Tools.convertRs(request.getParameter("sContent")));
		tbWxMenu.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxMenu.setNWxMenuId(Tools.convertRi(request.getParameter("wxMenuId")));
		tbWxMenu.setNtype(Tools.convertRi(request.getParameter("ntype")));

		if (!picUrl.equals("1")) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("txtpath");

			if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
				String filenameold = file.getOriginalFilename();
				String hz = filenameold.substring(filenameold.lastIndexOf(".", filenameold.length()), filenameold.length());

				if (hz.equalsIgnoreCase(".JPG") || hz.equalsIgnoreCase(".PNG")) {

					String newfilename = Tools.radomName(2) + hz;
					InputStream input = file.getInputStream();

					String folderPath = propertiesFile.getImagefolderPath() + tbWxMenu.getNUserId() + "\\";
					if (Tools.upload(newfilename, input, folderPath)) {
						picUrl = propertiesFile.getImageUrlPath() + tbWxMenu.getNUserId() + "/" + newfilename;
					}

				} else {
					result = 3;
					response.getWriter().print("{save:'true',success:'" + result + "'}");
					return;
				}
			}
		}

		tbWxMenu.setSPicUrl(picUrl);
		result = adminSiteService.updateSiteMenu(tbWxMenu);

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 菜单删除
	 */
	@RequestMapping(value = "/module/main/delAdminSiteMenu.do")
	public void delAdminSiteMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int nWxMenuId = Tools.convertRi(request.getParameter("ids"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.delSiteMenu(nWxMenuId);
		response.getWriter().print(result);
	}

	/**
	 * 文章管理 
	 */
	/**
	 * 添加文章记录
	 */
	@RequestMapping(value = "/module/main/saveAdminSiteText.do")
	public void saveAdminSiteText(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败 
		 */
		int result = 2;
		
		int userId=Tools.convertRi(request.getParameter("userid"));

		TbWxText tbWxText = new TbWxText();
		tbWxText.setDCreateTime(new Date());
		tbWxText.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxText.setNUserId(userId);
		tbWxText.setSContent(Tools.convertRs(request.getParameter("sContent")));
		tbWxText.setSRandom(Tools.radomName(1));
		tbWxText.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxText.setSUrl(propertiesFile.getTpTextUrl()+"?userid="+userId+"&srandom="+tbWxText.getSRandom());
		
		if(tbWxText.getNUserId()<=0){
			result = 4;
			response.getWriter().print("{save:'true',success:'" + result + "'}");
			return;
		}
		
		result = adminSiteService.saveSiteText(tbWxText);

		// uploadTemplate(request, radomName());

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 查询文章消息 ntype：类型（1有效2无效）
	 */
	@RequestMapping(value = "/module/main/searchAdminSiteText.do")
	public void searchAdminSiteText(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		int userid = Tools.convertRi(request.getParameter("userid"));
		int ntype = Tools.convertRi(request.getParameter("ntype"));
		Page page = adminSiteService.searchSiteText(pr, userid, ntype);
		List tblist = (List) page.getResult();
		ListRange resultList = new ListRange();
		resultList.setList(tblist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		String result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList);
		response.getWriter().print(result);
	}

	/**
	 * 修改文章记录
	 */
	@RequestMapping(value = "/module/main/updateAdminSiteText.do")
	public void updateAdminSiteText(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;

		TbWxText tbWxText = new TbWxText();
		tbWxText.setNIsValid(Tools.convertRi(request.getParameter("nisValid")));
		tbWxText.setSContent(Tools.convertRs(request.getParameter("sContent")));
		tbWxText.setSTitle(Tools.convertRs(request.getParameter("sTitle")));
		tbWxText.setNWxTextId(Tools.convertRi(request.getParameter("nwxTextId")));

		result = adminSiteService.updateSiteText(tbWxText);

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}

	/**
	 * 文章删除
	 */
	@RequestMapping(value = "/module/main/delAdminSiteText.do")
	public void delAdminSiteText(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int nwxTextId = Tools.convertRi(request.getParameter("ids"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.delSiteText(nwxTextId);
		response.getWriter().print(result);
	}
	
	/**
	 * 自定义菜单
	 */
	
	/**
	 * 查询自定义菜单
	 */
	@RequestMapping(value = "/module/main/searchAdminCustomMenu.do")
	public void searchAdminCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int userid = Tools.convertRi(request.getParameter("userid"));
		String result=adminSiteService.searchCustomMenu(userid);
		response.getWriter().print(result);
	}
	
	/**
	 * 保存自定义菜单
	 */
	@RequestMapping(value = "/module/main/saveAdminCustomMenu.do")
	public void saveAdminCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败 
		 */
		int result = 2;
		int userId=Tools.convertRi(request.getParameter("userid"));
		
		TbWxCustomMenu tbWxCustomMenu=new TbWxCustomMenu();
		tbWxCustomMenu.setNKey(Tools.convertRi(request.getParameter("nKey")));
		tbWxCustomMenu.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxCustomMenu.setNPid(Tools.convertRi(request.getParameter("nPid")));
		tbWxCustomMenu.setNtype(Tools.convertRi(request.getParameter("ntype")));
		tbWxCustomMenu.setSName(Tools.convertRs(request.getParameter("sName")));
		tbWxCustomMenu.setSRemark(Tools.convertRs(request.getParameter("sRemark")));
		tbWxCustomMenu.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxCustomMenu.setDCreateTime(new Date());
		tbWxCustomMenu.setSWxUserUrl("");
		tbWxCustomMenu.setNUserId(userId);

		result = adminSiteService.saveCustomMenu(tbWxCustomMenu);

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}
	
	/**
	 * 修改自定义菜单
	 */
	@RequestMapping(value = "/module/main/updateAdminCustomMenu.do")
	public void updateAdminCustomMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 必须，否则会抛异常
		response.setContentType("text/html");
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;

		int userId=Tools.convertRi(request.getParameter("userid"));
		
		TbWxCustomMenu tbWxCustomMenu=new TbWxCustomMenu();
		tbWxCustomMenu.setNWxCustomMenuId(Tools.convertRi(request.getParameter("nWxCustomMenuId")));
		tbWxCustomMenu.setNKey(Tools.convertRi(request.getParameter("nKey")));
		tbWxCustomMenu.setNOrder(Tools.convertRi(request.getParameter("nOrder")));
		tbWxCustomMenu.setNtype(Tools.convertRi(request.getParameter("ntype")));
		tbWxCustomMenu.setSName(Tools.convertRs(request.getParameter("sName")));
		tbWxCustomMenu.setSRemark(Tools.convertRs(request.getParameter("sRemark")));
		tbWxCustomMenu.setNWxUserUrlId(Tools.convertRi(request.getParameter("nWxUserUrlId")));
		tbWxCustomMenu.setSWxUserUrl("");
		tbWxCustomMenu.setNUserId(userId);
		

		result = adminSiteService.updateCustomMenu(tbWxCustomMenu);

		response.getWriter().print("{save:'true',success:'" + result + "'}");
	}
	
	/**
	 * 自定义菜单删除
	 */
	@RequestMapping(value = "/module/main/delAdminCustomMenu.do")
	public void delAdminCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int nWxCustomMenuId = Tools.convertRi(request.getParameter("ids"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.delCustomMenu(nWxCustomMenuId);
		response.getWriter().print(result);
	}
	
	/**
	 * 自定义菜单同步
	 */
	@RequestMapping(value = "/module/main/syncAdminCustomMenu.do")
	public void syncAdminCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int userId=Tools.convertRi(request.getParameter("userid"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.syncCustomMenu(userId);
		response.getWriter().print(result);
	}
	
	/**
	 * 自定义菜单删除
	 */
	@RequestMapping(value = "/module/main/delAdminSyncCustomMenu.do")
	public void delAdminSyncCustomMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int userId=Tools.convertRi(request.getParameter("userid"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.delSyncCustomMenu(userId);
		response.getWriter().print(result);
	}
	
	/**
	 * 首页模版更换
	 */
	@RequestMapping(value = "/module/main/updateAdminSiteTemplate.do")
	public void updateAdminSiteTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int userId=Tools.convertRi(request.getParameter("userid"));
		int nTemplateId = Tools.convertRi(request.getParameter("ids"));
		/**
		 * result 返回值：1.成功 2.失败
		 */
		int result = 2;
		result = adminSiteService.updateSiteTemplate(userId,nTemplateId);
		response.getWriter().print(result);
	}
	/**
	 * 首页模版查询
	 */
	@RequestMapping(value = "/module/main/selectAdminSiteTemplate.do")
	public void selectAdminSiteTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int userId=Tools.convertRi(request.getParameter("userid"));
		int result = adminSiteService.selectSiteTemplate(userId);
		response.getWriter().print(result);
	}
	
}